package cn.how2go.api.controller;


import cn.how2go.api.common.CommonResult;
import cn.how2go.api.common.ConePo;
import cn.how2go.api.common.MessageResult;
import cn.how2go.api.entity.Cone;
import cn.how2go.api.entity.Device;
import cn.how2go.api.entity.Fence;
import cn.how2go.api.service.ConeService;
import cn.how2go.api.service.DeviceService;
import cn.how2go.api.service.FenceService;
import cn.how2go.api.util.DateUtil;
import cn.how2go.api.vo.ConGroup;
import cn.how2go.api.vo.ConeType;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2020-05-31
 */
@Api(value = "锥筒",description = "锥筒信息的管理")
@RestController
@RequestMapping("/api/cone")
public class ConeController {
    @Autowired
    private ConeService coneService;

    @Autowired
    private FenceService fenceService;

    @ApiOperation(value="查询锥筒信息列表", notes="")
    @RequestMapping(value = "listCone", method = RequestMethod.GET)
    public CommonResult listCone(){
        EntityWrapper<Cone> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("state",0);
        entityWrapper.orderBy("CreateTime",false);
        List<Cone> list = coneService.selectList(entityWrapper);
        return CommonResult.success(list);
    }


    @ApiOperation(value="添加锥筒信息", notes="")
    @RequestMapping(value = "saveCone", method = RequestMethod.POST)
    public MessageResult saveCone(@RequestBody Cone param){
        //验证
        String termId = param.getTermID();
        if(termId==null ||termId.trim().equals("")) {
            return MessageResult.getError("500","锥桶编号不能为空");
        }

        //验证锥桶编号是否存在
        EntityWrapper<Cone> entityWrapper0 = new EntityWrapper<>();
        entityWrapper0.eq("`TermID`",termId);
        List<Cone> list0 = coneService.selectList(entityWrapper0);
        if(list0!=null &&list0.size()>0) {
            return MessageResult.getError("500","锥桶编号已存在");
        }

        //验证
        String group  = param.getGroup();
        if(group==null ||group.trim().equals("")) {
            return MessageResult.getError("500","锥桶分组不能为空");
        }
        //同一分组不能有不同类型的锥桶
        EntityWrapper<Cone> entityWrapper3 = new EntityWrapper<>();
        entityWrapper3.eq("`Group`",param.getGroup());
        Cone groupCone = coneService.selectOne(entityWrapper3);

        if(groupCone!=null && (groupCone.getType() != param.getType())){
            if(param.getType() == 1) {
                return MessageResult.getError("500", "锥桶" + param.getGroup() + "组，已为单独生成，不能再为按组生成");
            }else{
                return MessageResult.getError("500", "锥桶" + param.getGroup() + "组，已为按组生成，不能再为单独生成");
            }
        }

        //验证
        Integer type = param.getType();
        if(type==null) {
            return MessageResult.getError("500","锥桶类型不能为空");
        }
        //验证锥桶序号同一组中不能重复是否存在
        Integer no = param.getNo();
        EntityWrapper<Cone> entityWrapper1 = new EntityWrapper<>();
        entityWrapper1.eq("`Group`",param.getGroup());
        entityWrapper1.ne("`TermID`", "");
        entityWrapper1.eq("`No`", no);
        List<Cone> list1 = coneService.selectList(entityWrapper1);
        if(list1!=null &&list1.size()>0) {
            return MessageResult.getError("500","锥桶序号不能重复");
        }
        //判断单独生成只能有一个


        if(param.getType() == 0){
            EntityWrapper<Cone> entityWrapper2 = new EntityWrapper<>();
            entityWrapper2.eq("`Group`",param.getGroup());
            List<Cone> list2 = coneService.selectList(entityWrapper2);
            if(list2!=null &&list2.size()>0) {
                return MessageResult.getError("500","锥桶类型为单独生成，同一组不能多于一个锥桶");
            }
        }

        param.setWorking(2);
        param.setState(0);
        param.setCreateTime(new Date());
        param.setLastTime(new Date());
        coneService.insert(param);
        return MessageResult.getSuccess("修改成功");
    }

    @ApiOperation(value="保存锥筒信息", notes="根据id修改锥筒信息")
    @RequestMapping(value = "editCone", method = RequestMethod.POST)
    public MessageResult editCone(@RequestBody Cone param){
        //验证
        String termId = param.getTermID();
        if(termId==null ||termId.trim().equals("")) {
            return MessageResult.getError("500","锥桶编号不能为空");
        }

        //验证锥桶编号是否存在
        EntityWrapper<Cone> entityWrapper0 = new EntityWrapper<>();
        entityWrapper0.eq("`TermID`",termId);
        entityWrapper0.ne("ID",param.getId());
        List<Cone> list0 = coneService.selectList(entityWrapper0);
        if(list0!=null &&list0.size()>0) {
            return MessageResult.getError("500","锥桶编号已存在");
        }

        //验证
        String group  = param.getGroup();
        if(group==null ||group.trim().equals("")) {
            return MessageResult.getError("500","锥桶分组不能为空");
        }

        //同一分组不能有不同类型的锥桶
        EntityWrapper<Cone> entityWrapper3 = new EntityWrapper<>();
        entityWrapper3.eq("`Group`",param.getGroup());
        entityWrapper3.ne("TermID","");
        entityWrapper3.ne("ID",param.getId());
        List<Cone> groupCone = coneService.selectList(entityWrapper3);
        if(groupCone!=null && groupCone.size()>0 && (groupCone.get(0).getType() != param.getType())){
            if(param.getType() == 1) {
                return MessageResult.getError("500", "锥桶" + param.getGroup() + "组，已为单独生成，不能再为按组生成");
            }else{
                return MessageResult.getError("500", "锥桶" + param.getGroup() + "组，已为按组生成，不能再为单独生成");
            }
        }

        //验证
        Integer type = param.getType();
        if(type==null) {
            return MessageResult.getError("500","锥桶类型不能为空");
        }
        //验证锥桶序号同一组中不能重复是否存在
        Integer no = param.getNo();
        EntityWrapper<Cone> entityWrapper1 = new EntityWrapper<>();
        entityWrapper1.eq("`Group`",param.getGroup());
        entityWrapper1.ne("`TermID`", "");
        entityWrapper1.eq("`No`", no);
        entityWrapper1.ne("ID",param.getId());
        List<Cone> list1 = coneService.selectList(entityWrapper1);
        if(list1!=null &&list1.size()>0) {
            return MessageResult.getError("500","锥桶序号不能重复");
        }

        //判断单独生成只能有一个
        if(param.getType() == 0){
            EntityWrapper<Cone> entityWrapper2 = new EntityWrapper<>();
            entityWrapper2.eq("`Group`",param.getGroup());
            entityWrapper2.ne("TermID","");
            entityWrapper2.ne("ID",param.getId());
            List<Cone> list2 = coneService.selectList(entityWrapper2);
            if(list2!=null &&list2.size()>0) {
                return MessageResult.getError("500","锥桶类型为单独生成，同一组不能多于一个锥桶");
            }
        }

        EntityWrapper<Cone> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ID",param.getId());
        param.setLastTime(new Date());
        coneService.update(param,entityWrapper);
        return MessageResult.getSuccess("修改成功");
    }

    @ApiOperation(value="查询锥筒组信息", notes="")
    @RequestMapping(value = "getGroup", method = RequestMethod.GET)
    public CommonResult getGroup(){
        List<ConGroup>  list = new ArrayList<>();
        Map<String,Integer> map = new HashMap<>();
        EntityWrapper<Cone> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("state",0);
        entityWrapper.orderBy("CreateTime",false);
        List<Cone> result = coneService.selectList(entityWrapper);
        for(Cone bean:result){
            String group = bean.getGroup();
            String fence = bean.getFence();
            if(fence!=null&&!"".equals(fence)){
                map.put(group,1);
            }else{
                map.put(group,0);
            }
        }
        for(Map.Entry<String, Integer> entry:map.entrySet()){
            ConGroup param = new ConGroup(entry.getKey(),entry.getValue());
            list.add(param);
        }
        return CommonResult.success(list);
    }

    @ApiOperation(value="删除锥筒信息", notes="根据id删除锥筒信息")
    @RequestMapping(value = "deleteCone", method = RequestMethod.GET)
    public MessageResult deleteCone(@RequestParam String id){
        EntityWrapper<Cone> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ID",id);
        Cone bean = coneService.selectOne(entityWrapper);
        if(bean==null){
            return MessageResult.getError("500","删除失败，锥桶可能已被删除");
        }
        Cone param = new Cone();
        param.setState(1);
        param.setTermID("");
        param.setGroup("0");
        coneService.update(param,entityWrapper);
        //修改围栏为失效
        EntityWrapper<Fence> fenceEntityWrapper = new EntityWrapper<>();
        fenceEntityWrapper.eq("ID",bean.getFence());
        Fence fence = new Fence();
        fence.setValid(0);
        fenceService.update(fence,fenceEntityWrapper);
        return MessageResult.getSuccess("删除成功");
    }

    @ApiOperation(value="保存锥筒位置信息", notes="根据id修改锥筒位置信息")
    @RequestMapping(value = "updateLocation", method = RequestMethod.POST)
    public MessageResult updateLocation(@RequestBody ConePo param){
        //System.out.println("【coneLocation】============="+param.toString());
        double zAlt = 0;
        //获取Z组锥桶
        Cone z = this.getZcone();
        if(z!=null){
            zAlt = z.getAlt();
        }
        //查询终端信息
        EntityWrapper<Cone> selectEntityWrapper = new EntityWrapper<>();
        selectEntityWrapper.eq("TermID",param.getTermID());
        Cone bean = coneService.selectOne(selectEntityWrapper);
        if(bean==null){
            return MessageResult.getError("500","没有此终端");
        }
        int status = param.getStatus();
        //Cone up = new Cone();
        bean.setLat(param.getLat());
        bean.setLon(param.getLon());
        bean.setLat2(param.getLat2());
        bean.setLon2(param.getLon2());
        bean.setLastTime(new Date());
        bean.setWorking(1);
        if(status!=4 && status!=5){
            //超过5分钟
            if(DateUtil.timepk(bean.getLastTime(),5*60)){
                bean.setAlt(param.getAlt());
                //相对高度
                bean.setHeight(param.getAlt()-zAlt);
            }
        }else{
            bean.setAlt(param.getAlt());
            //相对高度
            bean.setHeight(param.getAlt()-zAlt);
        }

        EntityWrapper<Cone> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("TermID",param.getTermID());
        coneService.update(bean,entityWrapper);
        return MessageResult.getSuccess("修改成功");
    }

    @ApiOperation(value="锥筒类型数量信息", notes="")
    @RequestMapping(value = "getConeTypeAll", method = RequestMethod.GET)
    public CommonResult getConeTypeAll(){
        List<ConeType> list = coneService.countByType();
        return CommonResult.success(list);
    }

    //获取Z组锥桶
    private Cone getZcone(){
        EntityWrapper<Cone> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("`Group`","Z");
        return coneService.selectOne(entityWrapper);
    }

    @ApiOperation(value="获取Z锥桶的高度", notes="")
    @RequestMapping(value = "findZcone", method = RequestMethod.GET)
    public CommonResult findZcone(){
        double zAlt = 0;
        Cone z = getZcone();
        if(z!=null){
            zAlt = z.getAlt();
        }
        return CommonResult.success(zAlt);
    }

    @ApiOperation(value="查询锥筒组信息除了Z", notes="")
    @RequestMapping(value = "getGroupExz", method = RequestMethod.GET)
    public CommonResult getGroupExz(){
        List<ConGroup>  list = new ArrayList<>();
        Map<String,Integer> map = new HashMap<>();
        EntityWrapper<Cone> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("state",0);
        entityWrapper.ne("`Group`","Z");
        entityWrapper.orderBy("CreateTime",false);
        List<Cone> result = coneService.selectList(entityWrapper);
        for(Cone bean:result){
            String group = bean.getGroup();
            String fence = bean.getFence();
            if(fence!=null&&!"".equals(fence)){
                map.put(group,1);
            }else{
                map.put(group,0);
            }
        }
        for(Map.Entry<String, Integer> entry:map.entrySet()){
            ConGroup param = new ConGroup(entry.getKey(),entry.getValue());
            list.add(param);
        }
        return CommonResult.success(list);
    }
}

